package com.panopset;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import com.panopset.compat.Strings;

/**
 *
 * HTTP GET client.
 *
 */
public final class HttpGETclient extends HttpClientAbstract {

    /**
     * @param urlString
     *            URL.
     */
    public HttpGETclient(final String urlString) {
        super(urlString);
    }

    /**
     * @param url
     *            URL.
     */
    public HttpGETclient(final URL url) {
        super(url);
    }

    /**
     * Get the text from a file represented by a URL.
     *
     * @return Text response from GET..
     */
    public String getResponse() {
        StringWriter sw = new StringWriter();
        InputStreamReader isr = null;
        BufferedReader br = null;
        String s = null;
        try {
            isr = new InputStreamReader(getConnection().getInputStream());
            br = new BufferedReader(isr);
            while ((s = br.readLine()) != null) {
                sw.append(s).append(Strings.getEol());
            }
        } catch (Exception e) {
            Util.log(e);
        } finally {
            closeConnection();
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e1) {
                Util.log(e1);
            }
            try {
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException e2) {
                Util.log(e2);
            }
        }
        return sw.toString();
    }

    @Override
    protected void setConnectionProperties(final HttpURLConnection con) {
        try {
            con.setRequestMethod("GET");
        } catch (ProtocolException e) {
            Util.log(e);
            throw new RuntimeException(e);
        }
    }
}
